<?php


namespace App\Services\Repo;

use App\EmptyModel;
use App\EmptyObject;
use App\Models\Company;
use App\Models\WxClient;
use App\Models\SimCard;
use Helper;
use App\Services\Interfaces\RepoServiceInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class CompanyRepo implements RepoServiceInterface
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];
    /**
     * @param array|null $_options
     * @return Model
     * <code>
     *  $repo->create(['name' => '']);
     * </code>
     */

    public function create(array $_options = null):Model {
        try {
            $opts = array_pull($_options, 'options', []);
            $company = Company::create($_options);
            $company->options = $opts;
            $company->save();
            return $company;
        } catch (\Exception $ex) {
            // todo write error to log
            logger($ex->getMessage());
            if (config('app.debug')) {
                throw $ex;
            }
            return new EmptyModel();
        }
    }

    public function read($limit = 0)
    {
        $inputs = Helper::get_filter();
        $searchCompanyName = array_get($inputs, 'name', false);
        $searchCompanyStatus = array_get($inputs, 'status', null);
        $query = Company::searchByStatus($searchCompanyStatus);
        if ($searchCompanyName) {
            $query = $query->searchByName($searchCompanyName);
        }

        return $query->orderBy('_id', 'desc')->paginate(20);
    }

    public function find(array $_filter)
    {
        $result = Company::withTrashed()->where($_filter)->first();
        if( is_null($result) ) {
            return new EmptyObject();
        } else {
            $result->wxClients;
            return $result;
        }
    }

    public function update(array $_filter, array $_update_data):bool
    {
        /** @var Company $company */
        $company = Company::withTrashed()->where($_filter)->first();
        return $company->update($_update_data);
    }

    public function delete(array $_filter):bool
    {
        // TODO: Implement delete() method.
    }
}
